package com.worm.base_upload_demo.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class FileUploadController {
  String str = "yyyy_MM_dd";

  SimpleDateFormat sdf = new SimpleDateFormat(str);


  @PostMapping("/upload")
  public Map<String, Object> fileUpload(MultipartFile file, HttpServletRequest req) {
    System.out.println(str);
    Map<String, Object> result = new HashMap<>();

    ArrayList<String> allowFileTypeList = new ArrayList<>();
    allowFileTypeList.add(".jpg");
    allowFileTypeList.add(".pdf");
    allowFileTypeList.add(".txt");


    String originalFilename = file.getOriginalFilename();

    String suffix = null;

    //检查是否在允许的文件列表里
    boolean isInTypeRange = false;
    for (String s : allowFileTypeList) {
      if (originalFilename != null && originalFilename.endsWith(s)) {
        suffix = s;
        isInTypeRange = true;
        break;
      }
    }

    if (!isInTypeRange) {
      result.put("status", "error");
      result.put("msg", "类型错误您不能为" + file.getContentType()) ;
      return result;
    }

    String archivePath = sdf.format(new Date());
    String savePath = req.getServletContext().getRealPath("/") + archivePath;

    File saveFolder = new File(savePath);

    System.out.println(savePath);
    if (!saveFolder.exists()) {
      saveFolder.mkdirs();
    }

    String newFileName = UUID.randomUUID().toString() + suffix;

    try {
      file.transferTo(new File(saveFolder, newFileName));

      result.put("status", "success");
      result.put("msg", "上传成功");
      result.put("url", req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/" + archivePath + "/" + newFileName);

    } catch (IOException e) {
      e.printStackTrace();

      result.put("status", "error");
      result.put("msg", e.getMessage());
    }

    return result;
  }
}
